#include <iostream>
#include <memory>
#include "Accpet.hpp"
#include "Connection.hpp"
#include "TcpServer.hpp"

#include "Socket.hpp"
void Usage(const string& s)
{
    cout << "\n\tUsage: " + s + " port\n\n"; 
}

class TcpServer;

int main(int argc,char* argv[]){

    if(argc != 2)
    {   
        Usage(argv[0]);
        return -1;
    }
    int port = atoi(argv[1]);
    //1. 创建TcpSocket的listen套接字，用于监听事件
    unique_ptr<Socket> listensock = std::make_unique<TcpSocket>();
    listensock->BuildListenSocketMethod(port,11);//启动服务器监听


    //创建TcpServer服务端和accept接收类，
    unique_ptr<TcpServer> svr = std::make_unique<TcpServer>();
    unique_ptr<Accept> accepter = std::make_unique<Accept>();
    auto listen_recv = std::bind(&Accept::AcceptConnection,accepter.get(),std::placeholders::_1);//将this（也就是accept.get原始指针）提前绑定到方法
    //把acceptconnection方法绑定给发生   
    //读（连接）事件就绪后的回调方法: listen_recv 
    //因为该TcpSock就是用来监听的，监听是否有新链接的，当有新链接时，TcpSocket的读事件就会就绪
    //从而就会调用acceptconnection函数进行accept服务器和客户端的连接

    //生成listen连接的连接Connection对象
    Connection* listenconn = ConnectionFactory::BuildListenConnection(listensock->GetSockfd(),listen_recv,(EPOLLIN|EPOLLET),svr.get());
    //设置为EPOLLIN 和 EPOLLET模式

    //添加事件
    svr->AddConnection(listenconn);

    //开启派发，查看是否有事件就绪
    svr->Dispatcher();
}